package com.ygg.service.Impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.ygg.service.MsmService;
import com.ygg.util.ConstantPropertiesUtils;
import com.ygg.util.EmailUtil;
import com.ygg.vo.msm.MsmVo;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

@Service
public class MsmServiceImpl implements MsmService {

    @Resource
    EmailUtil emailUtil;

    @Override
    public boolean send(String phone, String code) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ConstantPropertiesUtils.ACCESS_KEY_ID)
                .accessKeySecret(ConstantPropertiesUtils.SECRECT)
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region(ConstantPropertiesUtils.REGION_Id) // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("尚医通平台")
                .templateCode("SMS_460960560")
                .phoneNumbers(phone)
                .templateParam("{\"code\":" + code + "}")
                .build();


        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        System.out.println(new Gson().toJson(resp));

        client.close();

        return true;
    }

    @Override
    public boolean send(MsmVo msmVo) {
        if (!StringUtils.isEmpty(msmVo.getPhone())) {
            emailUtil.sendMessage("2719464548@qq.com",
                    msmVo.getParam().get("title").toString(),
                    msmVo.getParam().get("reserveDate").toString());
            return true;
        }

//        if(!StringUtils.isEmpty(msmVo.getPhone())) {
//            String code = (String)msmVo.getParam().get("code");
//            return this.send(msmVo.getPhone(),code);
//        }
        return false;
    }

}
